package cn.fz.mpdemo.interceptor;

import cn.fz.mpdemo.domain.vo.ResultVO;
import cn.fz.mpdemo.utils.HttpUtils;
import cn.fz.mpdemo.utils.JwtUtils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTPayload;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局登陆验证拦截
 */
@Slf4j
@Component
public class LoginValidateInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求url
        String url = request.getRequestURL().toString();
        log.info("url: {}",url);
        // 2.判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if (url.contains("login")) {
            log.info("登录放行...");
            return true;
        }
        if (request.getRequestURI().contains("swagger")
                || request.getRequestURI().contains("api-docs")
                || request.getRequestURI().equals("/doc.html")
                || request.getRequestURI().equals("/favicon.ico")
                || request.getRequestURI().endsWith(".js")
                || request.getRequestURI().endsWith(".css")
        ) {
            log.info("knife4j放行...");
            return true;
        }
        // 3.获取请求头中的令牌（token）
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)){
            ResultVO error = ResultVO.failed("NOT_LOGIN");
            HttpUtils.responseWriter(response,error);
            // String errStr = JSONUtil.toJsonStr(error);
            // response.setContentType("application/json;charset=utf-8");
            // response.getWriter().write(errStr);
            return false;
        }

        // 4.判断令牌如果是不存在以及过期,返回错误结果（未登录）
        JWTPayload jwtPayload = null;
        try {
            jwtPayload = JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.info("解析令牌失败: {}",e.getMessage());
            ResultVO error = ResultVO.failed("NOT_LOGIN");
            HttpUtils.responseWriter(response,error);
            return false;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("id",jwtPayload.getClaim("id"));
        map.put("name",jwtPayload.getClaim("name"));
        map.put("username",jwtPayload.getClaim("username"));
        request.setAttribute("userInfo", map);
        return true;
    }
}
